package database;

import java.io.*;
import java.sql.*;
import userInterface.Login;
public class DataAccessorServerImpl {//implements DataAccessor{
	private PreparedStatement pstmtQuery;
	private Statement insertStatement;
	Connection connection;
	private String id = "";
	private String psw = "";
	public DataAccessorServerImpl(){
		initialzeDB();
	}
	public void setId(String id){
		this.id = id;
	}
	public String getId(){
		return this.id;
	}
	public void setPsw(String psw){
		this.psw = psw;
	}
	public String getPsw(){
		return this.psw;
	}
	private void initialzeDB(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("Driver loaded");
			
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost/test");
			System.out.println("Database Connected");
			
			String queryString = "select id, psw, totalScore, highestScore " +
								 "from player " 	+ 
								 "where id = ? and psw = ?;";
			
			pstmtQuery = connection.prepareStatement(queryString);
			insertStatement = connection.createStatement();
			
			DatabaseMetaData dbMetaData = connection.getMetaData();
			ResultSet rsTables = dbMetaData.getTables(null, null, null, 
					new String[]{"TABLE"});
			System.out.println("user tables: ");
			
			while(rsTables.next()){
				System.out.println(rsTables.getString("TABLE_NAME") + " ");
			}
			
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public boolean fetch(Login login){
		try{
			
			setId(login.getId());
			setPsw(login.getPassword());
			
			pstmtQuery.setString(1, id);
			pstmtQuery.setString(2, psw);
			ResultSet rset = pstmtQuery.executeQuery();
	
			if(rset.next()){
				String id = rset.getString(1);
				String psw = rset.getString(2);
				String totalScore = rset.getString(3);
				String highestScore = rset.getString(4);
				
				System.out.println(id + " " + psw + " " + totalScore + " " + highestScore);
				return true;
			}
			else{
				System.out.println("Empty");
				return false;
			}
		}
		catch(SQLException ex){
			ex.printStackTrace();
			return false;
		}
	}
	public boolean save(Login login){
		setId(login.getId());
		setPsw(login.getPassword());
		try{
			String insertString = "insert into player (id, psw, totalScore, highestScore) " + 
								  "values ( "+ "'" + id + "'" + "," + "'" + psw + "'" + "," + 
								  0 + "," + 0 + ");"; 
								  		       
			insertStatement.execute(insertString);
			return true;
		}
		catch(SQLException ex){
			return false;
		}
	}	
	public void close(){
		try{
			connection.close();
		}
		catch(Exception ex){
			
		}
	}
	public void initialData(){
		
	}
	public static void main(String[] args){
		DataAccessorServerImpl ds = new DataAccessorServerImpl();
		ds.setId("geligeliwang");
		ds.setPsw("123456");
	}
}
